package com.jr.controller;

import com.jr.pojo.User;
import com.jr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/program")
@CrossOrigin(origins = "*")
public class ProgramController {

    @Autowired
    private UserService userService;

    @GetMapping("login")
    @ResponseBody
    public Map<String, Object> login(@RequestParam String username, @RequestParam String password, @RequestParam(required = false) String userType){
        System.out.println("Login request received for username: " + username);
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建用户对象进行验证
            User loginUser = new User();
            loginUser.setUsername(username);
            loginUser.setPassword(password); // 原始密码，Service层会进行加密验证
            
            // 使用UserService进行验证
            User authenticatedUser = userService.queryByUser(loginUser);
            
            if (authenticatedUser != null) {
                // 登录成功，清除密码信息后返回
                authenticatedUser.setPassword(null);
                
                result.put("success", true);
                result.put("message", "Login successful");
                result.put("data", authenticatedUser);
                System.out.println("Login successful for user: " + authenticatedUser.getUsername() + ", type: " + authenticatedUser.getUserType());
            } else {
                result.put("success", false);
                result.put("message", "Invalid username or password");
                System.out.println("Login failed for username: " + username);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "Login failed: " + e.getMessage());
            System.err.println("Login error: " + e.getMessage());
        }
        
        return result;
    }

}